function scrollToTop(){
	scrollTo(0,0);
}

function findParentWithClass(el, className, checkCurrent){
	if(isString(el)) el = document.getElementById(el);
	var body = document.body;
 	
 	if(checkCurrent === false) el = el.parentNode;
	while(true){
		if(el == body) return false;

		if(el.className && el.className.search(className) != -1) return el;
		else el = el.parentNode;
	}
}

function findParentWithId(el, id){
	if(isString(el)) el = document.getElementById(el);
	var body = document.body;

	el = el.parentNode;
	while(true){
		if(el == body) return false;
		if(el.getAttribute('ID')){ //Se o elemento atual tem o atributo id
			if(id){
				if(el.getAttribute('ID') == id) return el;
			}else return el; //Se um id não foi especificado, retorna o elemento
		}
		else el = el.parentNode;
	}
}

function isString(input){
    return typeof(input)=='string';
}

function isObject(input){
	if(input == null) return false;
    return typeof(input)==='object';
}

function isNumeric(input){
    return input == parseFloat(input);
}

function isArray(input){
    return isObjectType('Array');
}

function isObjectType(input,type){
	if(Object.prototype.toString.call(input) == '[object '+type+']') return true;
    return false;
}

function isBoolean(input){
	return (input === true || input === false);
}


//find distance of element to the top border of the page
function findTopDistance(el){
	if(isString(el)) el = document.getElementById(el);

	var currentElTop = el.offsetTop;
	var currentTopDistance = currentElTop;
	while(el.parentNode){	
		el = el.parentNode;

		currentElTop = el.offsetTop;
		if(isNumeric(currentElTop)) currentTopDistance += currentElTop;
	}

	return currentTopDistance;
}

function getGetParameter(param){
	var url = location.href;
	
	var paramsStartPos = url.indexOf('?');
	if(paramsStartPos != -1){
		var parametersString = url.substr(paramsStartPos+1);
		
		var parametersList = parametersString.split('&');
		for(var i=0, iMax=parametersList.length; i<iMax; i++){
			var currentParameter = parametersList[i];
			
			var parameterParts = currentParameter.split('=');
			var name = parameterParts[0];
			var value = parameterParts[1];
			
			if(name == param) return value;
		}
	}
	
	return null;
}

//remove the target parameters set in the array passed to this function, of the URL
function removeGetParameter(targets){
	var url = location.href;
	var paramsStartPos = url.indexOf('?');
	var isTarget, paramName = '';
	
	if(paramsStartPos != -1){
		var newParamsList = new Array();
		var newParamsString = '';
		var paramsString = url.substr(paramsStartPos+1);
		var paramsList = paramsString.split('&');

		for(var i = 0, len = paramsList.length; i<len; i++){
			var array = paramsList[i].split('=');
			paramName = array[0];
			isTarget = false;

			for(var ii = 0, targetsLen = targets.length; i<targetsLen; i++){
				if(paramName == targets[ii]){
					isTarget = true;
					break;	
				} 
			}

			if(!isTarget) newParamsList.push(paramsList[i]);	
		}

		var path = url.substr(0, paramsStartPos+1); //endereço sem os parâmetros
		var newParamsString = newParamsList.join('&'); //nova lista de parametros

		if(newParamsString == '') path = path.substr(0, path.length-1); //remove o ? se não houverem mais params
		//if(path.charAt(path.length-1) == '#') path = path.substr(0, path.length-1); //necessário? Remove a tralha

		location.href = path+newParamsString;
	}
}

//return an array with associative keys of the parameters in the URL
function retrieveArrayGetParams(){
	var url = location.href;
	var paramsStartPos = url.indexOf('?');

	if(paramsStartPos != -1){
		var stringGet = url.substr(paramsStartPos+1);
		var arrayGetParams = new Array();

		var array = stringGet.split('&');
		for(var i = 0, arrayLen = array.length; i < arrayLen; i++){
			var arrayParts = array[i].split('=');
			
			arrayGetParams[arrayParts[0]] = arrayParts[1];
		}

		return arrayGetParams;
	}else return false;
}

//change the value of the target parameter in the URL
function changeGetParameter(name, value){
	if(!value){
		var parts = name.split('=');
		name = parts[0];
		value = parts[1];
	}

	var url = location.href;
	var paramsStartPos = url.indexOf('?');
	var paramsString = url.substr(paramsStartPos);
	var paramList = paramsString.split('&');
	var newParamList = new Array();

	for(var i=0, len = paramList.length; i<len; i++){
		var currentParam = paramList[i];
		var currentParamParts = currentParam.split('=');
		var currentParamName = currentParamParts[0];
		var currentParamValue = currentParamParts[1];

		if(currentParamName == name){
			if(currentParamValue = value) return false;
			currentParamValue = value;
		}
		newParamList.push(currentParamName+'='+currentParamValue);
	}

	var newParamsString = newParamList.join('&');

	location.href = url.substr(0, paramsStartPos)+newParamsString;
}

//add a new parameter to the URL
function addGetParameter(name, value){
	var url = location.href;
	var paramsStartPos = url.indexOf('?');

	var paramString = (value) ? name+'='+value : name;

	if(paramsStartPos != -1){
		if(url.substr(paramsStartPos).search(name) != -1){ //caso já exista este parâmetro
			changeGetParameter(name, value);
			return false;
		}else paramString = '&'+paramString;	
	} 
	else{ //se não houver ? não há parametros Get
		paramString = '?'+paramString;
		if(url.charAt(url.length-1) != '#') paramString = '#'+paramString; //Se não houver #, é necessário colcoar para não recarregar
	} 

	location.href = location.href + paramString;
}

//Troca a classe do elemento passado ou do elemento com o ID passado pela classe informada
//Se uma classe alvo for informada, e ele possuir a classe, substitui pela nova classe. 
//Caso não possua a classe alvo, apenas substitui todas pela nova.
function changeClass(el, newClassName, targetClass){
	if(isString(el)) el = document.getElementById(el);

	if(targetClass && el.className && el.className.search(targetClass) != -1){ //se foi enviado uma classe pra substituir e ela está no elemento
		var classes = el.className.split(' ');
		var newClasses = new Array();

		for(var index in classes){
			var currentClassName = classes[index];
			if(currentClassName != targetClass) newClasses.push(currentClassName);
		}

		newClasses.push(newClassName);
		newClassName = newClasses.join(' ');
	} 

	el.className = newClassName;
}

//Verifica se o elemento ou o elemento o ID informado possui alguma classe. 
//Se enviar uma classe alvo, verifica se ele possui essa classe alvo.
function hasClass(el, targetClassName){
	if(isString(el)) el = document.getElementById(el);

	if(el.className){
		if(targetClassName){
			if(el.className.search(targetClassName) != -1) return true;
			else return false;
		}
		else return true;
	}

	return false;
}

//make the target element empty
function clearElement(el){
	if(isString(el)) el = document.getElementById(el);

	el.innerHTML = '';
}

//return an object with the size and height of the element passed containing the text passed
function getTextSizeInElement(el, text){
	var currentText = el.innerHTML;
	var currentHeight = el.offsetHeight;

	el.innerHTML = text;
	el.style.visibility = 'hidden';
	el.style.height = 'auto';

	var elWidth = el.offsetWidth;
	var elHeight = el.offsetHeight;
	
	el.style.height = currentHeight+'px';
	el.innerHTML = currentText;
	el.style.visibility = 'visible';

	return {width: elWidth, height: elHeight}
}

//remove the class given of the element passed
function removeClass(el, targetClass){
	if(isString(el)) el = document.getElementById(el);

	var newClasses = new Array();
	if(el.className){
		var classesArray = el.className.split(' ');
		for(var i=0, len=classesArray.length; i<len; i++){
			var currentClass = classesArray[i];
			if(currentClass != targetClass && currentClass != '') newClasses.push(currentClass);
		}

		el.className = newClasses.join(' ');
		return true;
	}else return false;
}

//add a new class to the target element
function addClass(el, targetClassName){
	if(isString(el)) el = document.getElementById(el);

	if(!hasClass(el, targetClassName)){
		if(el.className){
			if(el.className.search(targetClassName) == -1){
				el.className += ' '+targetClassName;
			}
		}else el.className = targetClassName;
	}
}

/*function createCombo(obj, id, defaultText, selected){
	if(!defaultText) defaultText = 'Select an item';

	var combo = document.createElement('SELECT');
	var defaultOption = document.createElement('OPTION');
	defaultOption.appendChild(document.createTextNode(defaultText));
	defaultOption.value = '';

	combo.appendChild(defaultOption);

	for(var key in obj){
		var value = obj[key].id;
		var text = obj[key].name;

		var option = document.createElement('OPTION');
		option.appendChild(document.createTextNode(text));
		option.value = value;

		combo.appendChild(option);

		if(value == selected) option.selected = true;
	}

	if(id){
		if(document.getElementById(id)){
			var oldEl = document.getElementById(id);
			combo.name = oldEl.name;
			oldEl.parentNode.replaceChild(combo, oldEl);
		}

		combo.id = id;
	}

	return combo;
}*/
//atualizada 7/1/13
function createCombo(obj, id, defaultText, selected){
	var combo = document.getElementById(id);

	if(!combo){
		var combo = document.createElement('SELECT');
		combo.id = id;
	}else{
		combo.innerHTML='';
	}

	if(defaultText != false){
		if(defaultText == null) defaultText = 'Select an item';

		var defaultOption = document.createElement('OPTION');
		defaultOption.appendChild(document.createTextNode(defaultText));
		defaultOption.value = '';

		combo.appendChild(defaultOption);
	}

	for(var key in obj){
		var value = obj[key].id;
		var text = obj[key].name;

		var option = document.createElement('OPTION');
		option.appendChild(document.createTextNode(text));
		option.value = value;

		combo.appendChild(option);

		if(value == selected) option.selected = true;
	}

	return combo;
}

function selectItemCombo(combo, item){
	if(isString(combo)) combo = document.getElementById(combo);
	var comboOptions = combo.getElementsByTagName('OPTION');

	for(var i = 0, len = comboOptions.length; i < len; i++){
		var option = comboOptions[i];
		if(option.value == item){
			option.selected = true;
			break;	
		}else option.selected = false;
	}
}

function getPosition(el){
	if(isString(el)) el = document.getElementById(el);

	var x = el.offsetLeft;
    var y = el.offsetTop;
    var width = el.offsetWidth;
    var height = el.offsetHeight;

    while(el = el.offsetParent){
        x += el.offsetLeft;
        y += el.offsetTop;
    }

    return { left: x, top: y, right: x+width, bottom: y+height };
}

function getScrollPosition(){
  var left = 0, top = 0;

  if( typeof( window.pageYOffset ) == 'number' ) {
    top = window.pageYOffset;
    left = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    top = document.body.scrollTop;
    left = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    top = document.documentElement.scrollTop;
    left = document.documentElement.scrollLeft;
  }

  return {top: top, left: left };
}

function arrayToJson(array){
	var jsonArray = new Array();
	var isObject = false;

	for(var key in array){
		var value = array[key];
		
		if(!isNumeric(key)) isObject = true;

		if(isArray(value)){
			value = arrayToJson(value);	
		}else if(!isNumeric(value)) value = '"'+value+'"';

		if(isObject) value = '"'+key+'"'+':'+value;

		jsonArray.push(value);
	}

	var jsonString = '';
	var separator = ['[',']'];
	if(isObject) separator = ['{','}'];

	jsonString = separator[0]+jsonArray.join(',')+separator[1];

	return jsonString;
}

function getBrowserSize(){
	var height = 0;
	var width = 0;

	if(document.body){
	    height = document.body.clientHeight;
	    width = document.body.clientWidth;
	}
	else if(document.documentElement && document.documentElement.clientHeight){
		height = document.documentElement.clientHeight;
	    width = document.documentElement.clientWidth;
	}
	else if(self.innerHeight && self.innerWidth){
		height = self.innerHeight;
    	width = self.innerWidth;
	}

	return {width: width, height: height};
}

//1/11


function getImagePath(src, withExtension){
	if(!isString(src)) src = src.src;

	var slashPos = src.lastIndexOf('/');
	var charsLength = null;

	var path = '';

	if(withExtension){
		var dotPos = src.lastIndexOf('.');
		charsLength = dotPos - slashPos - 1;
		path = src.substr(slashPos+1, charsLength);
	}else path = src.substr(slashPos+1);
	
	
	return path;
}

function removeClassFromSet(className, targetClassName, step, targetParent){
	if(!targetParent) targetParent = document;
	else if(isString(targetParent)) targetParent = document.getElementById(targetParent);

	var set = targetParent.getElementsByClassName(className);
	for(var i =0, iMax = set.length; i<iMax;i++){
		var item = set[i];
		
		if(hasClass(item, 'selected')){
			if(step){
				if(i+step < iMax && i+step >= 0){
					removeClass(item, targetClassName);
					return set[i+step];
				}
			}else{
				removeClass(item, targetClassName);
				return null;
			}

			break;
		}
	}

	return null;
}

function checkExceptionList(value, list){
	if(!isArray(list)){
		list = [];
	}
	
	for(var i=0, iMax=list.length; i<iMax; i++)
		if(list[i] == value) return true;

	return false;
}

// 4/11
function replaceAll(string, snippet, replace){
	while (string.indexOf(snippet) != -1) string = string.replace(snippet, replace);
	return string;
}

// 7/11
function refreshCurrentPage(){
	location.href = location.href;
}

//8/11 atualizado 1/1/13

function setEvent(el, type, func, bubble){
	if(isString(el)) el = document.getElementById(el);
	//if(bubble == null || bubble == undefined) bubble = false;
	if(!bubble) bubble = false;

	el.addEventListener(type,func,bubble);
}

function setData(el, name, value){
	if(value == null) value = '1';
	el.setAttribute('DATA-'+name.toUpperCase(), value);
}

function getData(el, name, value){
	var attribute = 'DATA-'+name.toUpperCase();

	if(el.getAttribute(attribute)) return el.getAttribute(attribute);
	return null;
}

//convert form to object
function formToObject(form, flag){
	var obj={};
	for (var i=0;i<form.elements.length;i++){
		var element = form.elements[i];
		//if flag is defined
		if(element.getAttribute('DISABLED')) continue;
		if(flag){
			//skip the current element if it doesn't have 'flag' as class or remove the flag and keep going
			if(!hasClass(element, flag)) continue;			
			else removeClass(element, flag);
		}
		if(element.type=='checkbox'){
			var bool = (element.checked == true) ? 1 : 0;
			obj[element.name] = bool;
		}else{
			obj[element.name]=element.value;
		}
	}
	return obj;
}
function objectToForm(form,data){
	for (var i in data){
		if(form.elements[i]){
			if(form.elements[i].type=='checkbox'){
				form.elements[i].checked=(data[i]=='1');
			}else if(form.elements[i].type=='select' || form.elements[i].type=='select-one'){
				for(var j=0;j<form.elements[i].options.length;j++){
					if(form.elements[i].options[j].value==data[i])form.elements[i].options[j].selected=true;
				}
			}else{
				form.elements[i].value=data[i];
			}
		}
	}
}

function captiliseFirstLetter(string, lowerCase){
	if(lowerCase) string = string.toLowerCase();
	return string.charAt(0).toUpperCase() + string.slice(1);
}

function loadUrl(address){
	if(!address) address = location.href;
	location.href = address;
}

function getIframe(iframe){
	if(isString(iframe)) iframe = document.getElementById(iframe);
	return iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document;
}

// 1/1/13
function createHiddenInput(name,value,className,id,parentElement){
	var input = document.createElement('INPUT');
	input.type = 'hidden';

	input.name = name;
	input.value = value;

	if(className) input.className = className;
	if(id) input.id = id;
	
	if(parentElement){
		if(isString(parentElement)) parentElement = document.getElementById(parentElement);
		parentElement.appendChild(input);
	}else return input;
}

function fillFields(form, obj){
	var elements = form.elements;

	for (var i=0;i<elements.length;i++){
		var field = elements[i];
		var fieldName = field.name;
		var fieldType = field.nodeName.toUpperCase();

		if(fieldType == 'INPUT' || fieldType == 'TEXTAREA'){
			if(obj[fieldName]){
				if(fieldType == 'INPUT' && field.type.toUpperCase() == 'CHECKBOX'){
					if(obj[fieldName] == 1) field.checked = true;
					else field.checked = false;
				}
				else field.value = obj[fieldName];
			} 
		}
		else if(fieldType == 'SELECT'){
			var value = obj[fieldName];
			if(!isNumeric(value)) value = value.id;
			selectItemCombo(field, value);
		}
	}
}

function clearFields(form){
	var elements = form.elements;
	
	for (var i=0;i<elements.length;i++){
		var field = elements[i];
		var fieldType = field.nodeName.toUpperCase();

		if(fieldType == 'INPUT' || fieldType == 'TEXTAREA'){
			if(fieldType == 'INPUT' && field.type.toUpperCase() == 'CHECKBOX') field.checked = false;
			else field.value = '';
		}
		
		else if(fieldType == 'SELECT'){
			selectItemCombo(field, '');
		}
	}
}

function collectionToArray(col){
	var array = new Array();

	for(var i=0,iMax=col.length; i<iMax; i++) array.push(col[i]);

	return array;
}

// 1/1/13
function callDynamicFunction(name, params){
	var execFunction = window[name];
	if(typeof execFunction === 'function') execFunction(params);
}

function preventScrolling(turnOn){
	if(turnOn){
		document.body.style.overflow = "hidden";
	}else document.body.style.overflow = "auto";
}

function getDate(date){
	var day, month, year, hour, minute, second;

	if(!date) date = new Date();

	if(isString(date)){
		if(date.indexOf(' ') != -1){
			var datetime = splitDatetime(date);
			
			day = datetime.day;
			month = datetime.month;
			year = datetime.year;
			hour = datetime.hour;
			minute = datetime.minute;
			second = datetime.second;
		}else{
			if(date.indexOf(':') != -1){
				var time = splitTime(date);

				hour = time.hour;
				minute = time.minute;
				second = time.second;

				day = month = year = null;
			}else{
				var date = splitDate(date);

				day = date.day;
				month = date.month;
				year = date.year;

				second = minute = hour = null;
			}
		}

		date = new Date(year,month-1,day,hour,minute,second);
	
	}else{
		day = fillLeft(date.getDate(),2);
		month = fillLeft(date.getMonth()+1,2);
		year = date.getFullYear();
		hour = fillLeft(date.getHours(),2);
		minute = fillLeft(date.getMinutes(),2);
		second = fillLeft(date.getSeconds(),2);
	}
	
	return {day: day, month: month, year: year, hour: hour, minute: minute, second: second, date: date};
}

function splitDate(input){
	var separator = (input.indexOf('-') != -1) ? '-' : '/';
	var day, month, year;
	var dateParts;

	if(input.indexOf('-') != -1){
		dateParts = input.split('-');

		day = dateParts[2];
		month = dateParts[1];
		year = dateParts[0];
	}else{
		dateParts = input.split('/');

		day = dateParts[0];
		month = dateParts[1];
		year = dateParts[2];
	}

	return {day: day, month: month, year: year};
}

function splitTime(input){
	var timeParts = input.split(':');
	
	return {hour: timeParts[0], minute:timeParts[1], second: timeParts[2]};
}

function splitDatetime(input){
	var parts = input.split(' ');

	var date = splitDate(parts[0]);
	var time = splitTime(parts[1]);

	return {day: date.day, month: date.month, year: date.year, hour: time.hour, minute: time.minute, second: time.second};
}

function fillLeft(input, size, str){
	if(!str) str = '0';
	
	for(var i = 0, iMax = size - input.toString().length; i<iMax; i++){
		input = str+input;
	}

	return input;
}

function getKeyCode(e){
	var keycode;
	
	if(window.event){
		keycode = (event.keyCode) ? event.keyCode : event.charCode;
	}
	else if(e) keycode = e.which;

	return keycode;
}

function getSize(element){
	var height, width;
	var removeHiddenParent = false;

	if(!element.parentNode){
		var hiddenParent = document.createElement('DIV');
		hiddenParent.style.visibility = 'hidden';
		
		document.body.appendChild(hiddenParent);
		hiddenParent.appendChild(element);

		removeHiddenParent = true;
	}

	height = element.offsetHeight;
	width = element.offsetWidth;

	if(removeHiddenParent) document.body.removeChild(hiddenParent);

	return {width: width, height: height};
}

function setCookie(c_name,value,exdays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name){
	var c_value = document.cookie;
	var c_start = c_value.indexOf(" " + c_name + "=");
	if (c_start == -1){
		c_start = c_value.indexOf(c_name + "=");
	}
	if (c_start == -1){
		c_value = null;
	}else{
		c_start = c_value.indexOf("=", c_start) + 1;
		var c_end = c_value.indexOf(";", c_start);
		if (c_end == -1) {
			c_end = c_value.length;
		}
		c_value = unescape(c_value.substring(c_start,c_end));
	}
	return c_value;
}

function sort(array,key,asc){
	if(!key) key = id;

	var byKey = false;

	for(var k in array){
		if(key in array[k]) byKey = true;
		else byKey = false;

		break;
	}

	if(byKey){
		if(asc == null) asc = true;

		if(asc){
			
			array.sort(function(a,b){
				if(a[key] < b[key]) return -1;
				else if(a[key] > b[key]) return 1;
				else return 0;
			});
			
		}else{
			array.sort(function(a,b){
				if(a[key] > b[key]) return -1;
				else if(a[key] < b[key]) return 1;
				else return 0;
			});
		}		
	}else array.sort();
	
	return array;
}

function copyVar(variable,recursively){
	var value;
	var copy = {};
	for(var key in variable){
		value = variable[key];

		if(recursively === true && isObject(value)){
			if('cloneNode' in value) value = value.cloneNode(true);
			else value = copyVar(value,true);	
		} 

		copy[key] = value;
	}

	return copy;
}

function isIE(){
	var userAgent = navigator.userAgent.toLowerCase();
	
	return (userAgent.indexOf('msie') != -1) ? parseInt(userAgent.split('msie')[1]) : false;
}